<script setup>
import Dialog from './components/dialog.vue'
</script>
<script>
export default {
  data (){
    return {
      list: JSON.parse(localStorage.getItem('list')) || [],
      dialogVisible: false,
      editIndex: undefined,
      editItem: null
    }
  },
  methods: {
    // 接收子组件信息，更新列表
    updateList () {
      this.list = JSON.parse(localStorage.getItem('list')) || []
    },
    // 点击删除

    handleDelete (index) {
      this.list.splice(index, 1)
      localStorage.setItem('list', JSON.stringify(this.list))
      this.updateList()
    },
    // 点击编辑
    handleEdit (index, item) {
      this.editIndex = index
      this.editItem = item
      this.dialogVisible = true
    },
    // 点击创建
    handleCreate () {
      this.dialogVisible = true
      this.editIndex = undefined
    }
  }
}
</script>

<template>
  <h1>本地的 todo list 代办清单</h1>
  <button class="create-btn" @click="handleCreate">创建</button>
  <!-- 表格 -->
  <table>
    <tbody>
        <tr style="color: #9c9899; font-weight: 700;">
            <td>内容</td>
            <td>时间</td>
            <td>操作</td>
        </tr>
        <!-- 循环列表项 -->
        <tr v-for="(item,index) in list" :key="index">
          <td>{{item.text}}</td>
          <td>{{item.time}}</td>
          <td>
            <button class="delete" @click="handleDelete(index)">删除</button>
            <button class="edit" @click="handleEdit(index, item)">编辑</button>
          </td>
        </tr>
    </tbody>
</table>

  <!-- 弹框 -->
  <Dialog v-model:dialogVisible="dialogVisible" @updateList="updateList" :editIndex="editIndex" :editItem="editItem"></Dialog>
</template>

<style scoped>
.create-btn {
  width: 60px;
  height: 34px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  border-radius: 5px;
}

table {
  width: 1500px;
}

tr {
  display: flex;
  border-bottom: 2px solid #f4f5f9;
  height: 50px;
  align-items: center;
}

td {
  flex: 1;
}

.delete, .edit {
  width: 60px;
  height: 34px;
  color: #fff;
  border: 0;
  border-radius: 5px;
  background-color: #f56c6c;
}
.edit {
  margin-left: 10px;
  background-color: #409eff;
}

button {
  cursor: pointer;
}

h1 {
  width: 600px;
}
</style>
